package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.entity.Room;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.mapper.RoomMapper;
import com.zzyl.mapper.RoomTypeMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BedServiceImpl implements BedService {

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private RoomTypeMapper roomTypeMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }

    @Override
    public void createBed(BedDto bedDto) {
        //床位编号不能重复
        if (bedMapper.selectByBedNumber(bedDto.getBedNumber()) != null){
            throw new BaseException(BasicEnum.BED_EXIST_FAIL);
        }

        Bed bed = new Bed();
        BeanUtil.copyProperties(bedDto, bed);
        bed.setBedStatus(0);
        bedMapper.insertBed(bed);

        if (bed != null){
            bedMapper.delectById(bed.getRoomId());
            Room room = roomMapper.selectById(bed.getRoomId());
            if (room != null){
                roomTypeMapper.addBedCount(room.getTypeName());
            }
        }
    }

    @Override
    public BedVo searchById(Long id) {
        Bed bed = bedMapper.selectById(id);
        BedVo bedVo = new BedVo();
        BeanUtil.copyProperties(bed, bedVo);
        return bedVo ;
    }

    @Override
    public void updateBed(BedDto bedDto) {
        //床位状态为0时才能修改
        if (bedMapper.selectById(bedDto.getId()).getBedStatus() != 0){
            throw new BaseException(BasicEnum.BED_INUSE_EDIT_FAIL);
        }

        //床位编号不能重复且可以等于本来的编号
        if (bedMapper.countDiffBedNumber(bedDto.getBedNumber(), bedDto.getId()) != null){
            throw new BaseException(BasicEnum.BED_EXIST_FAIL);
        }
        Bed bed = new Bed();
        BeanUtil.copyProperties(bedDto, bed);
        bedMapper.updateById(bed);
    }

    @Override
    public void deleteById(Long id) {
        Bed bed = bedMapper.selectById(id);
        if (bed != null){
            bedMapper.delectById(id);
            Room room = roomMapper.selectById(bed.getRoomId());
            if (room != null){
                roomTypeMapper.decrBedCount(room.getTypeName());
            }
        }
    }
}

